package cn.shenzz.hot100.leetcode_49;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();

        for (String str : strs) {
            int[] count = new int[26];
            for (int i = 0; i < str.length(); ++i) {
                ++count[str.charAt(i) - 'a'];
            }
            StringBuilder buffer = new StringBuilder();
            for (int i = 0; i < 26; ++i) {
                if (count[i] != 0) {
                    buffer.append((char)('a' + i));
                    buffer.append(count[i]);
                }
            }

            String key = buffer.toString();
            List<String> list = map.getOrDefault(key, new ArrayList<String>());
            list.add(str);
            map.put(key, list);
        }
        return new ArrayList<>(map.values());
    }
}